<template>
  <div class="page-container">
    <div class="page-breadcrumb">
      <router-link to="/main">
        <div class="back">
          <img src="@/assets/images/back_icon.png" alt="返回按钮" />
        </div>
      </router-link>
      <div class="text">知识库</div>
    </div>
    <div class="page-content">
      <div class="left tree-box">
        <el-aside>
          <el-tree
            ref="eventCategoryTree"
            :data="eventCategoryTree"
            :props="defaultProps"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
            :render-content="renderContent"
            :expand-on-click-node="false"
          >
          </el-tree>
        </el-aside>
      </div>
      <div class="table-list">
        <div class="table-title">
          <h2>{{ triggerCurrenNode.name }}</h2>
          <div class="search-box">
            <div class="s-input">
              <input
                type="text"
                v-model="formData.keywords"
                placeholder="请输入关键字搜索"
              />
              <img
                src="@/assets/images/search.png"
                alt="搜索按钮"
                @click="searchSub"
              />
            </div>
            <div class="add-btn">
              <img
                src="@/assets/images/add_btn.png"
                alt="新增知识库"
                title="新增知识库"
                @click="addPersonnel"
              />
            </div>
          </div>
        </div>
        <div class="table-box">
          <el-table v-loading="loading" element-loading-text="数据下载中" :data="tableData" stripe style="width: 100%">
            <el-table-column
              type="index"
              width="60px"
              label="序号"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="fileCode"
              label="文件代号"
              align="center"
              min-width="100px"
            ></el-table-column>
            <el-table-column prop="fileName" label="文件名称" align="center" min-width="200px">
              <template v-slot="{ row }">
                <a href="javascript:;" @click="openFile(row)">{{
                  row.fileName
                }}</a>
              </template>
            </el-table-column>
            <el-table-column
              prop="version"
              label="版本号"
              align="center"
              min-width="100px"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="发布时间"
              align="center"
              width="130px"
            ></el-table-column>
            <el-table-column prop="download" label="下载" align="center" width="70px">
              <template v-slot="{ row, $index }">
                <div class="btn-list">
                  <el-button
                    class="btn-text"
                    type="text"
                    @click="downloadHandle(row, $index)"
                    >下载</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="video" label="播放" align="center" width="70px">
              <template v-slot="{ row }">
                <div class="btn-list">
                  <img
                    v-if="row.fileType == 1"
                    src="@/assets/images/play-video.png"
                    class="play-video"
                    @click="openFile(row)"
                    alt=""
                  />
                  <span v-else>-</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark1"
              label="备注1"
              align="center"
              min-width="100px"
            ></el-table-column>
            <el-table-column
              prop="remark2"
              label="备注2"
              align="center"
              min-width="100px"
            ></el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <div
                  class="option-icon del"
                  @click="delKnowledge(scope.row.id)"
                >
                  删除
                </div>
                <div
                  class="option-icon change"
                  @click="editKnowledge(scope.row)"
                >
                  修改
                </div>
                <!-- <el-button
                  @click="handleClick(scope.row)"
                  type="text"
                  size="small"
                  >查看</el-button
                >
                <el-button type="text" size="small">编辑</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-box">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-size="formData.pageSize"
            :total="total"
            :page-sizes="sizes"
            @size-change="sizeCurrentChange"
            @current-change="pageCurrentChange"
          >
          </el-pagination>
          <!-- <el-pagination
            background
            layout="total, prev, pager, next"
            :page-size="formData.pageSize"
            :total="total"
            @current-change="pageCurrentChange"
          >
          </el-pagination> -->
        </div>
      </div>
    </div>
    <!--新增类型节点弹窗-->
    <el-dialog
      class="add-event-dialog modify-class"
      :title="departDialogType == 'edit' ? '编辑' : '新增'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="addEventdialogVisible"
      size="tiny"
    >
      <el-form
        ref="addEventForm"
        :model="addEventForm"
        :rules="addEventNodeRules"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="addEventForm.name"></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="addEventForm.sortNum"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button class="btn-comfirm" type="primary" @click="addEventFormSubmitBtn('addEventForm')">确认</el-button>
        <el-button class="btn-cancel" @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>

    <!--知识库弹窗-->
    <el-dialog
      :title="knowDialogTitle == 'edit' ? '编辑' : '新增'"
      class="add-event-dialog modify-class"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="knowlVisible"
    >
      <el-form
        ref="knowForm"
        :model="knowForm"
        :rules="knowFormRules"
        label-width="100px"
      >
        <el-form-item style="margin-top: 20px;" label="上传文件" prop="fileId">
          <div>
            <upload-attach
              style="margin-left: 10px"
              accept=""
              @upload-success="uploadSuccess"
            />
          </div>
          <!-- <el-input v-model="knowForm.fileId"></el-input> -->
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="knowForm.fileName"></el-input>
        </el-form-item>
        <el-form-item label="文件代号" prop="fileCode">
          <el-input v-model="knowForm.fileCode"></el-input>
        </el-form-item>
        <!-- <el-form-item label="类型名称" prop="typeId">
          <el-input v-model="knowForm.typeName" disabled></el-input>
        </el-form-item> -->
        <el-form-item label="版本号" prop="version">
          <el-input v-model="knowForm.version"></el-input>
        </el-form-item>
        <el-form-item label="备注1">
          <el-input
            type="textarea"
            :rows="4"
            v-model="knowForm.remark1"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注2">
          <el-input
            type="textarea"
            :rows="4"
            v-model="knowForm.remark2"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button class="btn-comfirm" type="primary" @click="knowFormSubmitBtn('knowForm')">确认</el-button>
        <el-button class="btn-cancel" @click="handlePersonnelCancel">取消</el-button>
      </div>
    </el-dialog>
    <video-dialog v-if="videoSrc" :src="videoSrc" @close="videoSrc = null" />
  </div>
</template>

<script>
import TreeRender from '@/components/treeOptions.vue'
import mainlistApi from '@/apis/overview/maillist.js'
import knowledgeApi from '@/apis/overview/knowledge.js'
import UploadAttach from '@/components/UploadAttach.vue'
import VideoDialog from '@/components/VideoDialog.vue'
import { exportFile } from '@/utils/index.js'
export default {
  components: { UploadAttach, VideoDialog },
  name: 'knowledge',
  data() {
    return {
      sizes: [5, 10, 20, 30, 40, 50, 100],
      eventCategoryTree: [], // 类型树
      defaultProps: {
        children: 'list',
        label: 'name',
      },
      formData: {
        type_id: '',
        keywords: '',
        pageNum: 1,
        pageSize: 10,
      },
      departDialogType: 'add',
      knowDialogTitle: 'add',
      /*触发的当前的节点，放到全局，方便调用*/
      triggerCurrenNodeData: {},
      /*触发的当前节点*/
      triggerCurrenNode: {},
      /*新增事件弹窗的输入框数据*/
      addEventdialogVisible: false,
      knowlVisible: false,
      addEventForm: {
        name: '',
        sortNum: '',
        parent_id: '',
        id: '', // 编辑必传
      },
      personnelForm: {},
      knowForm: {},
      knowFormRules: {
        fileCode: [
          { required: true, message: '请输入文件代号', trigger: 'change' },
        ],
        fileName: [
          { required: true, message: '请输入文件名称', trigger: 'change' },
        ],
        fileId: [{ required: true, message: '请上传文件', trigger: 'change' }],
        version: [
          { required: true, message: '请输入版本号', trigger: 'change' },
        ],
        typeId: [
          { required: true, message: '请输入所属分类', trigger: 'change' },
        ],
      },
      addEventNodeRules: {
        name: [
          { required: true, message: '请输入类型名称', trigger: 'change' },
        ],
      },
      loading: false,
      tableData: [],
      total: 0,
      videoSrc: '',
    }
  },
  created() {
    this.getDepartTree() // 查询类型树
    this.getKnowInfoList() // 知识库列表
  },
  mounted() {},
  methods: {
    uploadSuccess(data) {
      console.log('data', this.knowForm)
      console.log('data', data)
      this.knowForm.fileId = data.id
      this.knowForm.fileName = data.fileName
    },
    downloadHandle(row) {
      exportFile(
        process.env.VUE_APP_BASE_API + '/attach/download',
        { id: row.fileId },
        ''
      )
    },
    // 打开文件
    openFile(row) {
      let url =
        process.env.VUE_APP_BASE_API + '/attach/download?id=' + row.fileId
      switch (row.fileType) {
        case '1':
          this.videoSrc = url
          break
        case '2':
          this.$imageView([url])
          break
        default:
          window.open(url)
      }
    },
    getDepartTree() {
      knowledgeApi.gettKnowTypeTree().then((res) => {
        console.log(res)
        if (res.code == '200') {
          this.eventCategoryTree = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 请求知识库列表
    getKnowInfoList() {
      this.loading = true;
      knowledgeApi.getKnowInfoList(this.formData).then((res) => {
        if (res.code == '200') {
          let resData = res.data
          if (resData.list && resData.list.length) {
            this.tableData = resData.list
          } else {
            this.tableData = []
          }
          this.total = resData.total ? resData.total : 0
        } else {
          this.tableData = []
          this.total = 0
          this.$message.error(res.msg)
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 搜索
    searchSub() {
      // if (this.formData.type_id == "") {
      //   this.$message.error("请先选择左侧类型列表！");
      //   return;
      // }
      this.getKnowInfoList()
    },
    sizeCurrentChange(size) {
      this.formData.pageSize = size
      this.getPersonnelList()
    },
    // 翻页
    pageCurrentChange(val) {
      this.formData.pageNum = val
      this.getKnowInfoList()
    },
    // 新增知识库
    addPersonnel() {
      const deptInfo = this.triggerCurrenNode
      console.log(deptInfo)
      if (deptInfo.id !== '' && deptInfo.id !== undefined) {
        // let personnelForm = this.personnelForm;
        this.knowForm = {
          fileCode: '',
          fileName: '',
          fileId: '',
          typeId: deptInfo.id,
          typeName: deptInfo.name,
          version: '',
          remark1: '',
          remark2: '',
          id: undefined,
        }
        this.knowDialogTitle = 'add'
        this.knowlVisible = true
      } else {
        this.$message.error('请先选择左侧类型！')
      }
    },
    // 删除知识库内容
    delKnowledge(id) {
      this.$confirm('确定要删除该知识库内容吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          knowledgeApi.delKnowInfo({ id: id }).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功！')
              this.getKnowInfoList()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 编辑知识库内容
    editKnowledge(row) {
      this.knowDialogTitle = 'edit'
      this.knowForm = JSON.parse(JSON.stringify(row));
      this.knowlVisible = true

      // knowledgeApi.gettKnowTypeDetail({ id: row.id }).then((res) => {
      //   if (res.code == '200') {
      //     this.knowDialogTitle = 'edit'
      //     this.knowForm = row || {}
      //     this.knowForm.type_name = res.data.name
      //     this.knowlVisible = true
      //   }
      // })
      // console.log(res)
      // this.knowForm.type_name = row.fileId;
      // this.knowForm = row;
      // this.knowDialogTitle = "edit";
      // this.knowlVisible = true;
    },
    // 提交知识库
    knowFormSubmitBtn(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          let dataPost = this.knowForm
          ;(this.knowDialogTitle == 'edit'
            ? knowledgeApi.updatetKnowInfo(dataPost)
            : knowledgeApi.addKnowInfo(dataPost)
          ).then((res) => {
            if (res.code == '200') {
              this.$message.success(
                this.knowDialogTitle == 'edit' ? '修改成功！' : '新增成功！'
              )
              this.knowlVisible = false
              this.getKnowInfoList()
            }
          })
        }
      })
    },
    /*渲染函数*/
    renderContent(h, { node, data, store }) {
      let that = this //指向vue
      return h(TreeRender, {
        props: {
          NODE: node,
          DATA: data,
          STORE: store,
        },
        on: {
          //新增
          Append: (s, d, n) => that.appendEvent(s, d, n),
          //删除节点
          Delete: (s, d, n) => that.removeEvent(s, d, n),
          //编辑
          WatchInfo: (s, d, n) => that.updateEvent(s, d, n),
        },
      })
    },
    // 类型被点击时
    handleNodeClick(data) {
      this.formData.type_id = data.id
      this.triggerCurrenNode = data
      this.getKnowInfoList()
    },
    /*树形控件添加节点，添加弹窗出现*/
    appendEvent(s, d, n) {
      let addEventForm = this.addEventForm
      addEventForm.name = ''
      addEventForm.sortNum = ''
      this.triggerCurrenNodeData = d
      this.departDialogType = 'add'
      this.addEventdialogVisible = true
    },
    /*树形控件编辑节点，添加弹窗出现*/
    updateEvent(s, d, n) {
      let addEventForm = this.addEventForm
      addEventForm.name = d.name
      addEventForm.sortNum = d.sortNum
      this.triggerCurrenNodeData = d
      this.departDialogType = 'edit'
      this.addEventdialogVisible = true
    },
    /*树形控件删除节点*/
    removeEvent(s, d, n) {
      this.$confirm('确定要删除该类型吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          knowledgeApi.deltKnowType({ id: d.id }).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功！')
              this.getDepartTree()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleCancel() {
      this.addEventdialogVisible = false
    },
    handlePersonnelCancel() {
      this.knowlVisible = false
    },
    /*节点新增，新增树形菜单事件分类弹窗，提交按钮*/
    addEventFormSubmitBtn(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          let dataPost = {
            name: this.addEventForm.name,
            sortNum: this.addEventForm.sortNum,
            parentId:
              this.departDialogType == 'add'
                ? this.triggerCurrenNodeData.id
                : undefined,
            id:
              this.departDialogType == 'edit'
                ? this.triggerCurrenNodeData.id
                : undefined,
          }
          ;(this.departDialogType == 'edit'
            ? knowledgeApi.updateKnowType(dataPost)
            : knowledgeApi.addtKnowType(dataPost)
          ).then((res) => {
            if (res.code == '200') {
              this.$message.success(
                this.departDialogType == 'edit' ? '修改成功！' : '新增成功！'
              )
              this.addEventdialogVisible = false
              this.getDepartTree()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
.page-container {
  .page-breadcrumb {
    height: 58px;
    width: 100%;
    padding: 0 30px;
    display: flex;
    background: #f9f9f9;
    box-shadow: 0px 3px 8px 0px rgba(122, 128, 159, 0.1);
    .back {
      display: flex;
      align-items: center;
      height: 100%;
      padding: 0 20px;
      cursor: pointer;
      img {
        width: 30px;
        height: 20px;
      }
    }
    .text {
      display: flex;
      align-items: center;
      margin-left: 17px;
      font-size: 26px;
      color: #111434;
      font-weight: 400;
    }
  }
  .page-content {
    background: linear-gradient(0deg, #e7e9f2 0%, #e7e9f2 100%);
    display: flex;
    overflow: hidden;
    .left {
      width: 340px;
      min-height: calc(100vh - 135px);
      background: #f2f3f7;
      box-shadow: 0px 3px 31px 1px rgba(95, 99, 115, 0.25);
      padding: 20px;
      /deep/.el-tree {
        background: none;
        .el-tree-node__expand-icon {
          font-size: 18px;
        }
        .el-tree-node__content {
          height: 35px;
        }
      }
      /deep/
        .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        background-color: #dee1eb;
      }
    }
    .table-list {
      flex: 1;
      padding: 17px 40px;
      .search-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .add-btn {
          cursor: pointer;
          img {
            height: 40px;
            width: 40px;
          }
        }
      }
      .table-title {
        margin: 10px 0;
        display: flex;
        justify-content: space-between;
        h2 {
          font-size: 24px;
          font-weight: 400;
          // text-decoration: underline;
          color: #111434;
        }
      }
      .table-box {
        .option-icon {
          width: 36px;
          height: 36px;
          display: inline-block;
          text-indent: -999px;
          overflow: hidden;
          cursor: pointer;
          &.del {
            background: url('../../../../assets/images/del_btn.png') center
              no-repeat;
            margin-right: 3px;
            &:hover {
              background: url('../../../../assets/images/del_btn_a.png') center
                no-repeat;
              background-size: 100%;
            }
            background-size: 100%;
          }
          &.change {
            background: url('../../../../assets/images/change_btn.png') center
              no-repeat;
            &:hover {
              background: url('../../../../assets/images/change_btn_a.png')
                center no-repeat;
              background-size: 100%;
            }
            background-size: 100%;
          }
        }
        /deep/ .el-table {
          thead {
            th {
              background: #d8dcea;
              font-size: 20px;
              color: #505971;
            }
          }
          tbody {
            td {
              font-size: 18px;
              color: #111434;
            }
          }
        }
      }
      .pagination-box {
        padding: 10px 0;
        text-align: center;
      }
    }
  }
}
input::-webkit-input-placeholder {
  color: #a8adb7;
}
input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #a8adb7;
}
input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #a8adb7;
}
input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #a8adb7;
}
// /deep/.el-tree-node__expand-icon.expanded {
//   transform: rotate(0deg);
// }
// /deep/.el-tree-node__expand-icon.is-leaf {
//   background: url('../../../../assets/images/tree_leaf.png') center no-repeat;
// }
::v-deep {
  .el-button--text {
    color: #285fe3;
    font-size: 18px;
    text-decoration: underline;
  }
  .el-scrollbar__wrap {
    background: #e6edfb;
  }
  .el-select-dropdown {
    background: #e6edfb;
  }
}
/deep/.el-select-dropdown__empty {
  background: #e6edfb;
}
a {
  color: #285fe3;
}
.el-table {
  background-color: transparent;
}
/deep/.el-table tr {
  position: relative;
  background: #ffffff;
  &.current-row,
  &.hover-row,
  &:hover {
    background-color: #e6edfb;
    td {
      position: relative;
      transition: none;
      background-color: #e6edfb;
      &:first-child {
        &::before {
          content: '';
          display: block;
          position: absolute;
          top: 0;
          left: 0;
          bottom: 0;
          width: 3px;
          background-color: rgb(65, 129, 255);
        }
      }
    }
  }
}
.tree-box {
  ::v-deep {
    .el-tree-node__children {
      position: relative;
      padding-left: 30px;
      &::before {
        content: '';
        border-left: 1px dashed #999999;
        height: calc(100%);
        position: absolute;
        left: 6px;
        top: 0px;
      }
      .el-tree-node {
        position: relative;
      }
      .el-tree-node__content {
        position: relative;
        padding-left: 0 !important;
        &::after {
          content: '';
          width: 24px;
          height: 0;
          border-bottom: 1px dashed #999999;
          position: absolute;
          right: calc(100% - 2px);
          top: 17px;
          z-index: 1;
        }
      }
    }
    .el-tree-node__children .el-tree-node:last-child::before {
      content: '';
      width: 4px;
      height: calc(100% - 18px);
      display: block;
      background-color: #f2f3f7;
      position: absolute;
      bottom: 0;
      left: -26px;
    }
    .el-tree-node__expand-icon {
      position: relative;
      width: 17px;
      height: 17px;
      // background: #23b1f0;
      padding: 0;
      margin-right: 5px;
      &.is-leaf {
        display: none;
      }
      &::before {
        content: '+';
        width: 17px;
        height: 17px;
        line-height: 15px;
        background: #285fe3;
        font-size: 15px;
        position: absolute;
        top: 1px;
        left: 0;
        color: #fff;
        text-align: center;
        z-index: 2;
      }
      &.expanded {
        transform: none;
        &::before {
          content: '-';
          line-height: 16px;
          font-size: 20px;
        }
      }
    }
  }
}
</style>
